package com.wfuhui.modules.order.service.impl;

import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.wfuhui.modules.member.dao.MemberDao;
import com.wfuhui.modules.member.entity.MemberEntity;
import com.wfuhui.modules.order.dao.OrderDao;
import com.wfuhui.modules.order.dao.OrderRefundDao;
import com.wfuhui.modules.order.entity.OrderEntity;
import com.wfuhui.modules.order.entity.OrderRefundEntity;
import com.wfuhui.modules.order.service.OrderRefundService;

import cn.binarywang.wx.miniapp.api.WxMaService;



@Service("orderRefundService")
public class OrderRefundServiceImpl implements OrderRefundService {
	@Autowired
	private OrderRefundDao orderRefundDao;
	@Autowired
	private OrderDao orderDao;
	@Resource(name = "wxPayService")
	private WxPayService wxService;
	
	@Autowired
	private MemberDao memberDao;
	@Override
	public OrderRefundEntity queryObject(Integer id){
		OrderRefundEntity orderRefund = orderRefundDao.queryObject(id);
		OrderEntity order = orderDao.queryObject(orderRefund.getOrderId());
		orderRefund.setOrder(order);
		return orderRefund;
	}
	
	@Override
	public List<OrderRefundEntity> queryList(Map<String, Object> map){
		return orderRefundDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return orderRefundDao.queryTotal(map);
	}
	
	@Override
	public void save(OrderRefundEntity orderRefund){
		orderRefundDao.save(orderRefund);
	}
	
	@Override
	public void update(OrderRefundEntity orderRefund){
		orderRefundDao.update(orderRefund);
	}
	
	@Override
	public void delete(Integer id){
		orderRefundDao.delete(id);
	}
	
	@Override
	public void deleteBatch(Integer[] ids){
		orderRefundDao.deleteBatch(ids);
	}

	@Override
	@Transactional
	public void refund(OrderRefundEntity orderRefund) throws WxPayException {
		WxPayRefundRequest request = new WxPayRefundRequest();
		request.setOutRefundNo(orderRefund.getRefundNumber());
		request.setOutTradeNo(orderRefund.getOrder().getOrderNumber());
		request.setTotalFee(orderRefund.getOrder().getTotalAmount().multiply(new BigDecimal(100)).intValue());
		request.setRefundFee(orderRefund.getTotalAmount().multiply(new BigDecimal(100)).intValue());
		request.setRefundDesc("商品退款");
		wxService.refund(request);
		OrderRefundEntity o = new OrderRefundEntity();
		o.setId(orderRefund.getId());
		o.setStatus(2);
		orderRefundDao.update(o);
		OrderEntity order = new OrderEntity();
		order.setId(orderRefund.getOrderId());
		order.setOrderStatus(5);
		orderDao.update(order);
	}
	
}
